<template>
  <div class="profile-container">
    <div class="page-header">
      <h2>个人中心</h2>
      <p>查看和管理您的个人信息</p>
    </div>

    <div class="profile-content">
      <a-spin :spinning="loading" tip="加载中...">
        <a-row :gutter="24">
          <!-- 左侧：用户基本信息 -->
          <a-col :span="16">
            <a-card title="基本信息" class="profile-card">
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="用户ID">
                {{ userInfo?.userId || '-' }}
              </a-descriptions-item>
              <a-descriptions-item label="真实姓名">
                {{ userInfo?.realName || '-' }}
              </a-descriptions-item>
              <a-descriptions-item label="账号">
                {{ userInfo?.accountNo || '-' }}
              </a-descriptions-item>
              <a-descriptions-item label="工号">
                {{ userInfo?.staffNo || '-' }}
              </a-descriptions-item>
              <a-descriptions-item label="手机号">
                {{ userInfo?.phone || '-' }}
              </a-descriptions-item>
              <a-descriptions-item label="短信手机号">
                {{ userInfo?.smsPhone || '-' }}
              </a-descriptions-item>
              <a-descriptions-item label="组织ID">
                {{ userInfo?.orgId || '-' }}
              </a-descriptions-item>
              <a-descriptions-item label="客户ID">
                {{ userInfo?.customerId || '-' }}
              </a-descriptions-item>
              <a-descriptions-item label="客户名称" :span="2">
                {{ userInfo?.customerName || '-' }}
              </a-descriptions-item>
            </a-descriptions>
          </a-card>

          <!-- 权限信息 -->
          <a-card title="权限信息" class="profile-card" style="margin-top: 24px;">
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="是否转移">
                <a-tag :color="userInfo?.isTransfer ? 'green' : 'red'">
                  {{ userInfo?.isTransfer ? '是' : '否' }}
                </a-tag>
              </a-descriptions-item>
              <a-descriptions-item label="是否领导">
                <a-tag :color="userInfo?.leader ? 'blue' : 'default'">
                  {{ userInfo?.leader ? '是' : '否' }}
                </a-tag>
              </a-descriptions-item>
              <a-descriptions-item label="业务标签" :span="2">
                <a-tag v-if="userInfo?.customerBizTag" :color="getTagColor(userInfo.customerBizTag.code)">
                  {{ userInfo.customerBizTag.message }}
                </a-tag>
                <span v-else>-</span>
              </a-descriptions-item>
            </a-descriptions>
          </a-card>
        </a-col>

        <!-- 右侧：操作区域 -->
        <a-col :span="8">
          <a-card title="操作" class="profile-card">
            <div class="action-buttons">
              <a-button type="primary" block @click="handleEditProfile" :loading="editLoading">
                <edit-outlined />
                编辑资料
              </a-button>
              <a-button block @click="handleChangePassword" style="margin-top: 12px;">
                <key-outlined />
                修改密码
              </a-button>
              <a-button block @click="handleRefresh" style="margin-top: 12px;">
                <reload-outlined />
                刷新信息
              </a-button>
            </div>
          </a-card>

          <!-- 系统信息 -->
          <a-card title="系统信息" class="profile-card" style="margin-top: 24px;">
            <a-descriptions :column="1" size="small">
              <a-descriptions-item label="登录时间">
                {{ loginTime }}
              </a-descriptions-item>
              <a-descriptions-item label="系统版本">
                v1.0.0
              </a-descriptions-item>
              <a-descriptions-item label="浏览器">
                {{ browserInfo }}
              </a-descriptions-item>
            </a-descriptions>
          </a-card>
        </a-col>
        </a-row>
      </a-spin>
    </div>

    <!-- 编辑资料Modal -->
    <a-modal
      v-model:open="editModalVisible"
      title="编辑资料"
      :width="600"
      @ok="handleEditConfirm"
      @cancel="handleEditCancel"
    >
      <a-form
        :model="editForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="真实姓名">
          <a-input v-model:value="editForm.realName" />
        </a-form-item>
        <a-form-item label="手机号">
          <a-input v-model:value="editForm.phone" />
        </a-form-item>
        <a-form-item label="短信手机号">
          <a-input v-model:value="editForm.smsPhone" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 修改密码Modal -->
    <a-modal
      v-model:open="passwordModalVisible"
      title="修改密码"
      :width="500"
      @ok="handlePasswordConfirm"
      @cancel="handlePasswordCancel"
    >
      <a-form
        :model="passwordForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="当前密码">
          <a-input-password v-model:value="passwordForm.currentPassword" />
        </a-form-item>
        <a-form-item label="新密码">
          <a-input-password v-model:value="passwordForm.newPassword" />
        </a-form-item>
        <a-form-item label="确认密码">
          <a-input-password v-model:value="passwordForm.confirmPassword" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { EditOutlined, KeyOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import { getCurrentUserInfo } from '../server/api';
import type { UserInfo } from '../server/type';

// 响应式数据
const userInfo = ref<UserInfo | null>(null);
const loading = ref(false);
const editLoading = ref(false);
const editModalVisible = ref(false);
const passwordModalVisible = ref(false);

// 编辑表单
const editForm = ref({
  realName: '',
  phone: '',
  smsPhone: ''
});

// 密码表单
const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 获取用户信息
const fetchUserInfo = async () => {
  loading.value = true;
  try {
    const result = await getCurrentUserInfo();
    if (result.success && result.result) {
      userInfo.value = result.result;
      console.log('获取用户信息成功:', result.result);
    } else {
      message.error(result.message || '获取用户信息失败');
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    message.error('获取用户信息失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 登录时间
const loginTime = ref(new Date().toLocaleString());

// 浏览器信息
const browserInfo = ref(navigator.userAgent.split(' ').slice(-2).join(' '));

// 获取标签颜色
const getTagColor = (code: string) => {
  const colorMap: { [key: string]: string } = {
    'ADMIN': 'red',
    'USER': 'blue',
    'MANAGER': 'green',
    'OPERATOR': 'orange'
  };
  return colorMap[code] || 'default';
};

// 编辑资料
const handleEditProfile = () => {
  if (!userInfo.value) {
    message.error('用户信息不存在');
    return;
  }
  
  editForm.value = {
    realName: userInfo.value.realName || '',
    phone: userInfo.value.phone || '',
    smsPhone: userInfo.value.smsPhone || ''
  };
  editModalVisible.value = true;
};

// 确认编辑
const handleEditConfirm = async () => {
  editLoading.value = true;
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 更新本地用户信息
    if (userInfo.value) {
      userInfo.value = { ...userInfo.value, ...editForm.value };
    }
    
    message.success('资料更新成功');
    editModalVisible.value = false;
  } catch (error) {
    message.error('更新失败，请重试');
  } finally {
    editLoading.value = false;
  }
};

// 取消编辑
const handleEditCancel = () => {
  editModalVisible.value = false;
  editForm.value = {
    realName: '',
    phone: '',
    smsPhone: ''
  };
};

// 修改密码
const handleChangePassword = () => {
  passwordForm.value = {
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  };
  passwordModalVisible.value = true;
};

// 确认修改密码
const handlePasswordConfirm = async () => {
  if (!passwordForm.value.newPassword) {
    message.error('请输入新密码');
    return;
  }
  
  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    message.error('两次输入的密码不一致');
    return;
  }
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    message.success('密码修改成功');
    passwordModalVisible.value = false;
    passwordForm.value = {
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    };
  } catch (error) {
    message.error('密码修改失败，请重试');
  }
};

// 取消修改密码
const handlePasswordCancel = () => {
  passwordModalVisible.value = false;
  passwordForm.value = {
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  };
};

// 刷新信息
const handleRefresh = async () => {
  await fetchUserInfo();
  message.success('信息刷新成功');
};

// 页面加载时获取用户信息
onMounted(() => {
  fetchUserInfo();
});
</script>

<style scoped>
.profile-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 64px);
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #262626;
}

.page-header p {
  margin: 0;
  color: #8c8c8c;
  font-size: 14px;
}

.profile-content {
  max-width: 1200px;
  margin: 0 auto;
}

.profile-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  padding: 8px 0;
}

:deep(.ant-descriptions-item-label) {
  font-weight: 500;
  color: #595959;
}

:deep(.ant-descriptions-item-content) {
  color: #262626;
}

:deep(.ant-card-head-title) {
  font-weight: 600;
  color: #262626;
}
</style>
